import {commandHandler, commandType} from "@/complie/commond";

export const vNodeToElement = (vNode) => {
  if (vNode.type === 'text') {
    return document.createTextNode(vNode.content);
  }

  if (vNode.type === 'comment') {
    return document.createComment(vNode.content);
  }

  if (vNode.tag === 'template') {
    // console.log('template进来了', vNode)
    const fragment = document.createDocumentFragment();
    for (const child of vNode.children) {
      fragment.appendChild(vNodeToElement(child));
    }
    return fragment;
  }

  const {tag, attrs, children} = vNode;
  if (tag === 'ul') {
    // 在这里能拿到属性集合，把他们转义
    console.log('ul vNode', vNode);

    // 需要抽离
    for (let i = 0; i < attrs.length; i++) {
      const item = attrs[i];
      if(item.name.startsWith('v-')){
        const state = {data: vNode, index: i};
        commandHandler[item[commandType]](state, item.name);
      }
    }
  }


  const element = document.createElement(tag);

  for (const {name, value} of attrs) {
    element.setAttribute(name, value);
  }

  const fragment = document.createDocumentFragment();
  for (const child of children) {
    const childElement = vNodeToElement(child);
    fragment.appendChild(childElement);
  }

  element.appendChild(fragment);

  return element;
};
